package com.ww.springboot.boot.javabase.proxy.cglib;

import net.sf.cglib.proxy.Dispatcher;
import net.sf.cglib.proxy.Enhancer;

public class EnhancerDispatcher {
 
    public static void main(String[] args) {
        CarFactory factory = new CarFactory();
        System.out.println("factory built");
        System.out.println(factory.car.getName());
        System.out.println(factory.car.getName());
    }
 
    static class Car {
        String name;
        Car() {
        }
 
        String getName() {
            return name;
        }
    }
 
    static class CarFactory {
        Car car;
 
        CarFactory() {
            car = carLazyProxy();
        }
 
        Car carLazyProxy() {
            //Dispatcher每次调用都会触发  -》 跟 MethodInterceptor 有啥区别?
            Enhancer enhancer = new Enhancer();
            enhancer.setSuperclass(Car.class);
            enhancer.setCallback((Dispatcher) () -> {
                System.out.println("prepare loading");
                Car car = new Car();
                car.name = "this is a car";
                System.out.println("after loading");
                return car;
            });
            return ((Car) enhancer.create());
        }
    }
}